package com.chinaway.dsp.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;

//import com.chinaway.util.ApiUtil;
//import com.chinaway.util.DateTimeUtils;

public class ApiUtil {
	public final static String DEFAULT_CHARSET = "UTF-8";
	public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	
	/*
	 * 组装请求参数，返回值为key1=value1&key2=value2形式
	 */
	public static String createRequestParam(Map<String, Object> map) {
		StringBuilder param = new StringBuilder();

		for (Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); it.hasNext();) {
			Map.Entry<String, Object> e = it.next();
			Object value = e.getValue();
			if (value != null) {
					try {
						value = URLEncoder.encode(value.toString(), DEFAULT_CHARSET);
					} catch (UnsupportedEncodingException ex) {
					}
				
				param.append("&").append(e.getKey()).append("=").append(value);
			}
		}
		return param.toString().substring(1);
	}
	
	/*
	 * 二行制转字符串
	 */
	private static String byte2hex(byte[] b) {

		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

	/*
	 * 签名方法，用于生成签名。
	 * 
	 * @param params 传给服务器的参数
	 * 
	 * @param secret 分配给您的APP_SECRET
	 */
	public static String sign(Map params, String secret) {
		String result = null;
		if (params == null)
			return result;

		// 将参数按key排序
		Set<String> keys = params.keySet();
		String[] ps = new String[keys.size()];
		int i = 0;
		for (String key : keys) {
			Object value = params.get(key);
			if (value != null) {
				ps[i++] = key + value.toString();
			}
		}
		if (i == 0)
			return result;
		String[] ss = new String[i];
		System.arraycopy(ps, 0, ss, 0, i);
		Arrays.sort(ss);
		
		// 将secret同时放在头尾，拼成字符串
		StringBuilder orgin = new StringBuilder(secret);
		for (int j = 0; j < ss.length; j++) {
			orgin.append(ss[j]);
		}
		orgin.append(secret);
		
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("UTF-8")));
		} catch (Exception ex) {
			throw new java.lang.RuntimeException("sign error !");
		}
		return result;
	}

	/*
	 * 得到返回的内容
	 */
	public static String getResult(String urlStr, String content) {
		URL url = null;
//		HttpsURLConnection connection = null;
		HttpURLConnection connection = null;
		String result = null;

		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();
//			connection = (HttpsURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
//			connection.setHostnameVerifier(new HostnameVerifier() {
//				@Override
//				public boolean verify(String hostname, SSLSession session) {
//					return true;
//				}
//			});
			connection.connect();
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.writeBytes(content);
			out.flush();
			out.close();
			
//			System.out.println(connection.getHeaderFields());
			String encoding = connection.getContentEncoding();
			InputStreamReader is  = null;
			BufferedReader reader = null;
			if("gzip".equals(encoding)){
				is = new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8");
				reader = new BufferedReader(is);
			}else{
				is = new InputStreamReader(connection.getInputStream(), "UTF-8");
				reader = new BufferedReader(is);
			}
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				StringBuffer buffer = new StringBuffer();
				String line = "";
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				reader.close();
				result = buffer.toString();
			} else {
				System.out.println("url:"+urlStr+",ResponseCode:"+connection.getResponseCode()+",ResponseMessage:"+connection.getResponseMessage());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return result;
	}
	
	public static String getResult(String apiUrl, String appKey, String appSecret, String method, String format, Map params) {
		params.put("app_key", appKey);
		params.put("method", method);
		params.put("format", format);
		
		// 时间戳
		params.put("timestamp", DateTimeUtils.datetime2Text(new Date()));
		// 生成签名
		String sign = sign(params, appSecret);
		// 组装协议参数sign
		params.put("sign", sign);
		
		String result = createRequestParam(params);
		return getResult(apiUrl, result);
	}
	
	static final String APP_KEY = "1088";
	static final String APP_SECRET = "httpx";
	public static void main(String[] args) throws Exception {
		String title=java.net.URLEncoder.encode("点火", "UTF-8");
		System.out.println("title="+title);
		Map apiparamsMap = new HashMap();
		apiparamsMap.put("datatype", 4);
		apiparamsMap.put("sysid", 38);
		apiparamsMap.put("version", 1.0);
		apiparamsMap.put("dataparam","{\"id\":\"4923\",\"title\":\"点火\",\"gpsno\":\"28392810\",\"updatetime\":1436534099000,\"createtime\":1436534099000,\"starttime\":1436236286000,\"endtime\":1436236286000,\"difftime\":0,\"lngstart\":\"69.783074\",\"latstart\":\"24.016357\",\"lngend\":\"0.0\",\"latend\":\"0.0\",\"speed\":\"0\",\"maxspeed\":null,\"distance\":0,\"alarmtype\":1,\"iccard\":\"null\",\"markerid\":null,\"driverno\":null,\"nextid\":0}");
		// 时间戳
//		apiparamsMap.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		apiparamsMap.put("timestamp", System.currentTimeMillis());
		// 生成签名
		String sign = ApiUtil.sign(apiparamsMap, APP_SECRET);
		// 组装协议参数sign
		apiparamsMap.put("sign", sign);
		apiparamsMap.put("method", "truck.handle.saveTruckEvent");
		
		String paramStr = ApiUtil.createRequestParam(apiparamsMap);
		paramStr=paramStr.replace("点火", title);
		System.out.println(paramStr);
		String str = ApiUtil.getResult("http://test.truck.g7s.chinawayltd.com/pushHandle.php", paramStr);
		System.out.println(str);
	}
}